package com.project.market.controller;

import com.project.market.db.domain.MarketSystem;
import com.project.market.service.AdminConfigService;
import com.project.market.service.impl.AdminConfigServiceImpl;
import com.project.market.util.JacksonUtil;
import com.project.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/config/*")
public class AdminConfigController extends HttpServlet {

    AdminConfigService adminConfigService = new AdminConfigServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String op = req.getRequestURI().replace(req.getContextPath() + "/admin/config/", "");
        if("mall".equals(op)){
            mall(req,resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String op = req.getRequestURI().replace(req.getContextPath() + "/admin/config/", "");
        if("mall".equals(op)){
            getMall(req,resp);
        }
    }

    private void getMall(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String,Object> map = adminConfigService.getMall();
        Object ok = ResponseUtil.ok(map);
        String s = JacksonUtil.writeValueAsString(ok);
        resp.getWriter().println(s);
    }

    private void mall(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Map<String,Object> map = new HashMap<>();

        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();

        String address = JacksonUtil.parseString(reqBody, "market_mall_address");
        map.put("market_mall_address",address);
        String latitude = JacksonUtil.parseString(reqBody, "market_mall_latitude");
        map.put("market_mall_latitude",latitude);
        String longitude = JacksonUtil.parseString(reqBody, "market_mall_longitude");
        map.put("market_mall_longitude",longitude);
        String name = JacksonUtil.parseString(reqBody, "market_mall_name");
        map.put("market_mall_name",name);
        String phone = JacksonUtil.parseString(reqBody, "market_mall_phone");
        map.put("market_mall_phone",phone);
        String qq = JacksonUtil.parseString(reqBody, "market_mall_qq");
        map.put("market_mall_qq",qq);

        MarketSystem marketSystem = adminConfigService.mall(map);
        if(marketSystem ==null){
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail()));
        }
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
    }
}
